<template>
  <div>
    <!-- 注册页面的头部 -->
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />
    <!--  内容 -->

    <div class="login-page-logo">
      <img src="../assets/logo.png" alt="" />
    </div>
    <!-- 表单开始  -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="rules.username"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="rules.password"
      />
      <div style="margin: 16px">
        <van-button round block type="info" color="#DB281F" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>

    <div>
        <router-link to="/reg">去注册</router-link>
    </div>

    <!-- 表单结束 -->
  </div>
</template>

<script>
import { Form, Field } from "vant";
import  rules from '@/common/validator'

export default {
  name: "reg",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
  },
  data() {
    return {
      username: "",
      password: "",
      rules
    };
  },
  methods: {
    onSubmit(val) {

      
       this.$http.post('/user/pub/login',val)
       .then(res=>{
           console.log(res)
           if(res.code==0){
             this.$toast('登录成功')
             let {token,tokenExpired,uid,userInfo} = res;

              localStorage.setItem('xl-token',token)
              localStorage.setItem('xl-tokenExpired',tokenExpired)
              localStorage.setItem('xl-uid',uid)
              localStorage.setItem('xl-userInfo',JSON.stringify(userInfo))
              
              //  把用户名存到本地  做个优化  下次来就不用输入了  

              //  全局的数据也改一下
            this.$root.token = token
            this.$root.uid = uid
            this.$root.userInfo = userInfo


           setTimeout(v=>{
              this.$router.back()
           },500)

          }else{
              this.$toast(res.msg||'登录失败')
           }


       })

    },
    // yanzheng(val) {

    //   return new Promise((v) => {
    //     setTimeout(() => {
    //       v(val > 20);
    //     }, 200);
    //   });

    // },


  },
};
</script>

<style lang="less">
// css预处理

.login-page-logo {
  width: 180px;
  height: 180px;
  margin: 50px auto 0;
  img {
    width: 180px;
  }
}
</style>